# coding=utf-8
import hashlib
import traceback

from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

from .club import Club
from .message import Message
from .. import db, login_manager
from .base import BaseModel


class User(UserMixin, BaseModel):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    nickname = db.Column(db.String(64), unique=True, index=True)
    phone = db.Column(db.String(64), unique=True, index=True)
    gender = db.Column(db.SmallInteger,  default=1)
    status = db.Column(db.SmallInteger,  default=1, doc='1正常状态，2封禁状态')
    password_hash = db.Column(db.String(128))
    avatar_hash = db.Column(db.String(100))
    address = db.Column(db.String(80))  # 网址
    ip = db.Column(db.String(15), default='', doc='ip')
    ip_loc = db.Column(db.String(80), default='', doc='IP地址')

    def __repr__(self):
        return '<User{}>'.format(self.username)

    @staticmethod
    def insert_user(email, username, password):
        user = User(email=email, username=username, password=password,
                    avatar=email)
        db.session.add(user)
        try:
            db.session.commit()
            return True, user
        except:
            print(traceback.format_exc())
            return False, None

    @staticmethod
    def update_avatar(user, email):
        user.avatar_hash = user.hash_avatar(email)
        try:
            db.session.commit()
            return True, user
        except:
            print(traceback.format_exc())
            return False, None

    @staticmethod
    def hash_avatar(email):
        url = 'https://cravatar.cn/avatar/'
        email_hash = hashlib.md5(email.encode('utf-8')).hexdigest()
        return f'{url}{email_hash}.png'

    @staticmethod
    def hash_password(password):
        return generate_password_hash(password)

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        if self.email is not None and self.avatar_hash is None:
            self.avatar_hash = hashlib.md5(
                self.email.encode('utf-8')).hexdigest()

    @property
    def avatar(self):
        raise AttributeError('avatar is not a readable attribute')

    @avatar.setter
    def avatar(self, email):
        self.avatar_hash = self.cravatar(email)

    def cravatar(self, email):
        url = 'https://cravatar.cn/avatar/'
        email_hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return f'{url}/{email_hash}.png'

    def gravatar(self, size=40, default='identicon', rating='g'):
        # if request.is_secure:
        #     url = 'https://secure.gravatar.com/avatar'
        # else:
        #     url = 'http://www.gravatar.com/avatar'
        url = 'http://gravatar.duoshuo.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating)


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
